﻿namespace MicroCloud.Systems.Extensions
{
    public static class FileExtension
    {
        public static IServiceCollection AddFile(this IServiceCollection services, FileOption fileOption)
        {
            services.AddSingleton<IMapTuple, FileAutoMapperConfiguration>();
            services.AddScoped<FileStore>();
            services.AddScoped<IFileStore<FileEntity>>(provider => provider.GetService<FileStore>());
            services.AddScoped<IFileSaveRecordStore<FileSaveRecord>>(provider => provider.GetService<FileStore>());
            services.AddScoped<IFileActionRecordStore<FileActionRecord>>(provider => provider.GetService<FileStore>());
            services.AddScoped<IFileService, FileService>();

            #region 解决文件上传Multipart body length limit 134217728 exceeded
            services.Configure<FormOptions>(x =>
            {
                x.ValueLengthLimit = int.MaxValue;
                x.MultipartBodyLengthLimit = long.MaxValue;
                x.MemoryBufferThreshold = int.MaxValue;
            });
            #endregion

            #region 文件访问方式配置
            //if (fileOption.Mappings != null && fileOption.Mappings.Length > 0)
            //{
            //    var provider = new FileExtensionContentTypeProvider();
            //    fileOption.Mappings.ToList().ForEach(map =>
            //    {
            //        provider.Mappings.Add(map.FileType, map.ContentType);
            //    });
            //    services.AddSingleton<IContentTypeProvider>(provider);
            //}
            #endregion

            return services;
        }

        public static void UseFile(this IApplicationBuilder app, FileOption fileOption)
        {
            FileServerOptions fileServerOptions = new()
            {
                FileProvider = new PhysicalFileProvider(fileOption.Root),
                RequestPath = new PathString(fileOption.RequestPath),
                EnableDirectoryBrowsing = fileOption.DirectoryBrowser, // 启用静态文件目录浏览
                EnableDefaultFiles = true,   //启用静态文件服务
                RedirectToAppendTrailingSlash = true,    // 是否补全路径末尾斜杠“/”，并重定向
            };

            if (fileOption.AllowOrigin)
            {
                //静态文件允许跨域访问
                fileServerOptions.StaticFileOptions.OnPrepareResponse = (c) =>
                {
                    c.Context.Response.Headers.Append("Access-Control-Allow-Origin", "*");  //允许跨域
                    //c.Context.Response.Headers.Append("Cache-Control", "public,max-age=600");   //设置http响应缓存为600秒
                };
            }
            app.UseFileServer(fileServerOptions);

            //DirectoryHelper.CreateIfNotExists(fileOption.Root);
            //var physicalFileProvider = new PhysicalFileProvider(fileOption.Root);
            //app.UseStaticFiles(new StaticFileOptions
            //{
            //    ServeUnknownFileTypes = true,
            //          
            //    FileProvider = physicalFileProvider,
            //    RequestPath = fileOption.RequestPath,
            //    ContentTypeProvider = app.ApplicationServices.GetService<IContentTypeProvider>(),
            //    OnPrepareResponse = (response) =>
            //    {
            //        if (fileOption.AllowOrigin)
            //        {
            //            //静态文件允许跨域
            //            response.Context.Response.Headers.Append("Access-Control-Allow-Origin", "*");
            //        }
            //    }
            //});

            //if (fileOption.DirectoryBrowser)
            //{
            //    app.UseDirectoryBrowser(new DirectoryBrowserOptions()
            //    {
            //        FileProvider = physicalFileProvider,
            //        RequestPath = fileOption.RequestPath,
            //    });
            //}
        }

    }
}
